﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;

namespace MiscLib
{
    public partial class SharpZipLib
    {
        ///// <summary>
        ///// 压缩文件
        ///// </summary>
        ///// <param name="ZipFileName">filename生成的文件的名称，如：C\123\123.zip</param>
        ///// <param name="listSourceFileName">要压缩的文件列表，包含路径</param>
        ///// <returns></returns>
        //public static bool Zip(string ZipFileName, List<string> listSourceFileName)
        //{
        //    try
        //    {
        //        using (ZipFile zip = ZipFile.Create(ZipFileName))
        //        {
        //            zip.BeginUpdate();
        //            //添加文件 
        //            foreach (string file in listSourceFileName)
        //            {
        //                zip.Add(file, CompressionMethod.Deflated);
        //            }
        //            zip.CommitUpdate();
        //        }
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}

        /// <summary>
        /// 功能：压缩文件（暂时只压缩文件夹下一级目录中的文件，文件夹及其子级被忽略）
        /// </summary>
        /// <param name="dirPath">被压缩的文件夹夹路径</param>
        /// <param name="zipFilePath">生成压缩文件的路径，为空则默认与被压缩文件夹同一级目录，名称为：文件夹名+.zip</param>
        /// <returns>是否压缩成功</returns>
        public static bool Zip(string zipFilePath, List<string> listSourceFileName)
        {
            try
            {
                using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
                {
                    s.UseZip64 = UseZip64.Off;
                    byte[] buffer = new byte[4096];
                    foreach (string file in listSourceFileName)
                    {
                        ZipEntry entry = new ZipEntry(Path.GetFileName(file));
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);
                        using (FileStream fs = File.OpenRead(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }
                    s.Finish();
                    s.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static bool GZip(string zipFilePath, string SourceFileName)
        {
            try
            {
                using (GZipOutputStream s = new GZipOutputStream(File.Create(zipFilePath)))
                {
                    //生成一个GZipOutputStream流，用来生成压缩文件。     
                    //因为GZipOutputStream由Stream派生，所以它可以赋给Stream。     
                    using (FileStream fs = File.OpenRead(SourceFileName))
                    {
                        //生成一个文件流，它用来打开要压缩的文件     
                        //可以使用System.IO.File的静态函数OpenRead来生成文件流     
                        byte[] writeData = new byte[fs.Length];
                        //指定缓冲区的大小     
                        fs.Read(writeData, 0, (int)fs.Length);
                        //读入文件     
                        s.Write(writeData, 0, writeData.Length);
                        //写入压缩文件     
                        s.Close();
                    }
                }
                //关闭文件  
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>解压文件</summary>
        /// <param name="file">压缩文件的名称，如：C:\123\123.zip</param>
        /// <param name="dir">dir要解压的文件夹路径</param>
        /// <returns></returns>
        public static bool UnZip(string file, string dir)
        {
            try
            {
                if (!File.Exists(file))
                    return false;

                dir = dir.Replace("/", "\\");
                if (!dir.EndsWith("\\"))
                    dir += "\\";

                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                using (ZipInputStream s = new ZipInputStream(File.OpenRead(file)))
                {
                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName = Path.GetFileName(theEntry.Name);

                        if (directoryName != String.Empty)
                            Directory.CreateDirectory(dir + directoryName);

                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(dir + theEntry.Name))
                            {
                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static bool UnGZip(string GZipfilename, string UnGZipfilename)
        {
            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(UnGZipfilename)))
                    Directory.CreateDirectory(Path.GetDirectoryName(UnGZipfilename));

                GZipInputStream s = new GZipInputStream(File.OpenRead(GZipfilename));
                FileStream streamWriter = File.Create(UnGZipfilename);

                int size = 2048;
                byte[] data = new byte[2048];
                while (true)
                {
                    size = s.Read(data, 0, data.Length);
                    if (size > 0)
                    {
                        streamWriter.Write(data, 0, size);
                    }
                    else
                    {
                        break;
                    }
                }

                streamWriter.Close();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }  
    }
}
